package io.github.lee.jel.ui.main.media

import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.core.content.res.ResourcesCompat
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.BaseQuickAdapter.Companion.EMPTY_VIEW
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.core.ui.BaseRefreshFragment
import io.github.lee.core.ui.databinding.ToolbarSimpleCenterTitleBinding
import io.github.lee.core.util.getColor
import io.github.lee.core.util.toPx
import io.github.lee.core.vm.err.ViewModelException
import io.github.lee.jel.R
import io.github.lee.jel.databinding.LayoutHomeEmptyBinding
import io.github.lee.jel.domain.po.JellyfinSession
import io.github.lee.jel.ui.folder.MediaFolderActivity
import io.github.lee.jel.ui.server.add.AddServerActivity
import io.github.lee.jel.utils.screenWidthDP

@AndroidEntryPoint
class MainMediaFragment : BaseRefreshFragment<MainMediaVM>() {

    //===Desc:=============================================================

    companion object {
        fun newInstance(): MainMediaFragment =
            MainMediaFragment()
    }


    override fun onCreateViewModel(): MainMediaVM =
        viewModels<MainMediaVM>().value

    override fun onCreateToolbar(): Toolbar =
        ToolbarSimpleCenterTitleBinding.inflate(layoutInflater)
            .apply {
                bg = ResourcesCompat.getColor(
                    resources,
                    R.color.main_background_grey,
                    null
                )
                title = getString(R.string.txt_my_media)
                titleColor = ResourcesCompat.getColor(resources, R.color.main_black, null)
            }
            .toolbar


    override fun onCreateEmpty(): ViewDataBinding =
        LayoutHomeEmptyBinding.inflate(layoutInflater)
            .apply {
                tvAdd.setOnClickListener {
                    AddServerActivity.start(mContext)
                }
            }

    override fun onCreateLayoutManager(): RecyclerView.LayoutManager =
        GridLayoutManager(mContext, if (screenWidthDP(mContext) > 600) 8 else 3)
            .also {
                it.spanSizeLookup = object
                    : SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {
                        return if (vm?.adapter?.getItemViewType(position) == EMPTY_VIEW) {
                            it.spanCount
                        } else {
                            1
                        }
                    }

                }
            }

    //===Desc:=============================================================

    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        enableRefresh = false
        enableLoadMore = false
    }

    override fun showEmpty(e: ViewModelException?) {
        super.showEmpty(e)
        Log.e(javaClass.simpleName, "show empty ${e}")
    }
    override fun onSetViewListener() {
        super.onSetViewListener()
        vm?.adapter?.setOnItemClickListener { _, _, position ->
            val item = vm?.adapter?.getItem(position)
            if (null == item) {
                toast(getString(R.string.error_application_error))
                return@setOnItemClickListener
            }
            MediaFolderActivity.start(mContext, item)
        }
        vm?.adapter?.addOnItemChildClickListener(R.id.ivDelItem,
            object : BaseQuickAdapter.OnItemChildClickListener<JellyfinSession> {
                override fun onItemClick(
                    adapter: BaseQuickAdapter<JellyfinSession, *>,
                    view: View,
                    position: Int
                ) {
                    val item = vm?.adapter?.getItem(position)
                    if (null == item) {
                        toast(getString(R.string.error_application_error))
                        return
                    }
                    vm?.deleteSession(item)
                }
            })
        vm?.adapter?.setOnItemLongClickListener(BaseQuickAdapter.OnItemLongClickListener<JellyfinSession> { _, _, position ->
            val item = vm?.adapter?.getItem(position)
            if (null == item) {
                toast(getString(R.string.error_application_error))
                return@OnItemLongClickListener false
            }
            toast("q01001")

            return@OnItemLongClickListener true
        })
    }


    override fun onSetViewData() {
        super.onSetViewData()
        injectMenu(R.menu.menu_main_media) {
            if (itemId == R.id.action_add) {
                AddServerActivity.start(mContext)
                true
            } else {
                false
            }
        }


        refreshLayout?.setBackgroundColor(getColor(R.color.main_background_grey))

        recyclerView?.setPadding(16.toPx(mContext), 0, 16.toPx(mContext), 0)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        val lm = recyclerView?.layoutManager
        if (lm is GridLayoutManager) {
            lm.spanCount = if (screenWidthDP(mContext) > 600) 8 else 3
        }

    }
}